package com.sk.weichat.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.NotificationManagerCompat;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.ui.base.ActivityStack;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/3/7 0007.
 */

public class AppUtils {

    /**
     * 判断app是否处于前台
     */
    public static boolean isAppForeground(Context context) {

        boolean isForeground = MyApplication.getInstance().mActivityCount > 0;

        //        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        //        if (!tasks.isEmpty()) {
        //            ComponentName topActivity = tasks.get(0).topActivity;
        //            if (!topActivity.getPackageName().equals(context.getPackageName())) {
        //                Log.e("xuan", "app是否处于前台: false");
        //                return false;
        //            }
        //        }
        //
        //        Log.e("xuan", "app是否处于前台:  true");
        Log.e("xuan", "app是否处于前台:  " + isForeground);
        return isForeground;
    }

    /*判断键盘是否打开*/
    public static boolean isSoftShowing(Activity mActivity) {
        //获取当前屏幕内容的高度
        int screenHeight = mActivity.getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        return screenHeight - rect.bottom != 0;
    }
    //隐藏软键盘
    public static void hideSoftKeyboard(Context context , EditText editText){
        if (editText == null || context == null)return;
        InputMethodManager imm = (InputMethodManager) context. getSystemService(context.INPUT_METHOD_SERVICE);
        if (imm == null)return;
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); //强制隐藏键盘
    }
    //显示软键盘
    public static void showSoftKeyboard(Context context , EditText editText){
        if (editText == null || context == null)return;
        InputMethodManager imm = (InputMethodManager)context. getSystemService(context.INPUT_METHOD_SERVICE);
        if (imm == null)return;
        imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 展开隐藏键盘
     */
    public static void openKeyboard(Activity mActivity) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) mActivity
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 0);

    }

    public static boolean isAppForeground1(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Service.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList = activityManager.getRunningAppProcesses();

        if (runningAppProcessInfoList == null) {
            Log.e("xuan", "isAppForeground: runningAppProcessInfoList false");
            return false;
        }

        for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcessInfoList) {
            if (processInfo.processName.equals(context.getPackageName()) && processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                Log.e("xuan", "isAppForeground:  true" + processInfo.processName);
                return true;
            }
        }

        Log.e("xuan", "isAppForeground:  false");
        return false;
    }

    /**
     * 方法描述：判断某一应用是否正在运行
     *
     * @param context 上下文
     * @return true 表示正在运行，false表示没有运行
     */
    public static boolean isAppRunning(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = activityManager.getRunningTasks(100);
        if (list.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.baseActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 方法描述：判断某一Service是否正在运行
     *
     * @param context     上下文
     * @param serviceName Service的全路径： 包名 + service的类名
     * @return true 表示正在运行，false 表示没有运行
     */
    public static boolean isServiceRunning(Context context, String serviceName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceInfos = am.getRunningServices(200);
        if (runningServiceInfos.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningServiceInfo serviceInfo : runningServiceInfos) {
            if (serviceInfo.service.getClassName().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断手机上是否存在该应用
     *
     * @param context
     * @param packetName
     * @return
     */
    public static boolean isAppInstalled(Context context, String packetName) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packetName, 0);
        } catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 检查是否支持跳转
     *
     * @param context
     * @param intent
     * @return
     */
    public static boolean isSupportIntent(Context context, Intent intent) {
        return context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0;
    }

    /**
     * 判断该应用是否打开通知栏
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // sdk >= 24
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
            return notificationManagerCompat.areNotificationsEnabled();
        }
        // 19<=sdk<24
        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();

        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class appOpsClass = null; /* Context.APP_OPS_MANAGER */

        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod("checkOpNoThrow", Integer.TYPE, Integer.TYPE, String.class);

            Field opPostNotificationValue = appOpsClass.getDeclaredField("OP_POST_NOTIFICATION");
            int value = (int) opPostNotificationValue.get(Integer.class);
            return ((int) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 判断该应用是否拥有悬浮窗权限
     *
     * @param context
     * @return
     */
    public static boolean checkAlertWindowsPermission(Context context) {
        try {
            Object object = context.getSystemService(Context.APP_OPS_SERVICE);
            if (object == null) {
                return false;
            }
            Class localClass = object.getClass();
            Class[] arrayOfClass = new Class[3];
            arrayOfClass[0] = Integer.TYPE;
            arrayOfClass[1] = Integer.TYPE;
            arrayOfClass[2] = String.class;
            Method method = localClass.getMethod("checkOp", arrayOfClass);
            if (method == null) {
                return false;
            }
            Object[] arrayOfObject = new Object[3];
            arrayOfObject[0] = 24;
            arrayOfObject[1] = Binder.getCallingUid();
            arrayOfObject[2] = context.getPackageName();
            int invoke = ((Integer) method.invoke(object, arrayOfObject));
            return invoke == AppOpsManager.MODE_ALLOWED;
        } catch (Exception ex) {
            ActivityStack.getInstance().exit();
            android.os.Process.killProcess(android.os.Process.myPid());
        }
        return false;
    }

    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取版本名称
     *
     * @return
     */
    public static String getAppVersion(Context context) {
        String versionName = null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static int getLocalVersionCode(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            Log.e("VersionInfo", "Exception", e);
        }
        return localVersion;
    }

    /**
     * sd卡获取下载路径
     *
     * @return /storage/emulated/0/Download/
     */
    public static String getDownloadPath() {
        return Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator;
    }

    /**
     * textview 字符串内容关键字变蓝色
     * str  字符串
     * keyword 关键字
     */
    public static SpannableStringBuilder TextColorkeywordByBule(Context mContext, String str, String keyword) {
        //判断str 是否包含 keyword
        boolean status = str.contains(keyword);
        if (status) {
            int fstart = str.indexOf(keyword);
            int fend = fstart + keyword.length();
            SpannableStringBuilder style = new SpannableStringBuilder(str);
            style.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.deep_purple)), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            return style;
        } else if (str.contains(keyword.toUpperCase())) {//关键字转换成小写
            int fstart = str.indexOf(keyword.toUpperCase());
            int fend = fstart + keyword.toUpperCase().length();
            SpannableStringBuilder style = new SpannableStringBuilder(str);
            style.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.deep_purple)), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            return style;
        } else if (str.contains(keyword.toLowerCase())) {//关键字转换成大写
            int fstart = str.indexOf(keyword.toLowerCase());
            int fend = fstart + keyword.toLowerCase().length();
            SpannableStringBuilder style = new SpannableStringBuilder(str);
            style.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.deep_purple)), fstart, fend, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            return style;
        } else {
            return null;
        }
    }

    /**
     * 返回text的长度，一个汉字算两个，数字和英文算一个
     *
     * @param text
     * @return
     */
    public static int judgeTextLength(String text) {
        if (TextUtils.isEmpty(text)) {
            return 0;
        }
        int count = 0;
        for (int i = 0; i < text.length(); i++) {
            char item = text.charAt(i);
            if (item < 128) {
                count++;
            } else {
                count += 2;
            }
        }
        return count;
    }

    /**
     * @author: czl
     * @description 将List集合用字符串，逗号隔开进行拼接
     * @date: 2019/9/18 17:44
     */
    public static String listToString(List<String> list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i) + ",");
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }
        // 两次点击按钮之间的点击间隔不能少于500毫秒
    private static final int MIN_CLICK_DELAY_TIME = 500;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobile(String number) {
    /*
    移动：134、135、136、137、138、139、150、151、152、157(TD)、158、159、178(新)、182、184、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、170、173、177、180、181、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String num = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1，"[34578]"代表第二位可以为3、4、5、7、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(number)) {
            return false;
        } else {
            //matches():字符串是否在给定的正则表达式匹配
            return number.matches(num);
        }
    }

    /**
     * 过滤换行
     */
    public static String replaceBlank(String src) {
        String dest = "";
        if (src != null) {
            Pattern pattern = Pattern.compile("\t|\r|\n|\\s*");
            Matcher matcher = pattern.matcher(src);
            dest = matcher.replaceAll("");
        }
        return dest;
    }
}
